import json
import jsonpath
import requests
from retrying import retry
from Logs.log import log1
from db_sql import insert_db
from utils import steel_url as url, headers, ste
from datetime import datetime, date


@retry(stop_max_attempt_number=3)
def request():
    resp = requests.get(url, headers=headers)
    html = resp.text
    return json.loads(html)


def parse(py):
    db_dict = {}
    # minPrice = py["data"]["result"][0]["minPrice"]
    minPrice = float(jsonpath.jsonpath(py, "$..minPrice")[0])/100
    db_dict["lower_price"] = str(minPrice)
    maxPrice = float(jsonpath.jsonpath(py, "$..maxPrice")[0])/100
    db_dict["higher_price"] = str(maxPrice)
    db_dict["avg_price"] = str((maxPrice + minPrice)/2)
    db_dict["unit"] = jsonpath.jsonpath(py, "$..unit")[0]
    db_dict["raw_name"] = jsonpath.jsonpath(py, "$..breedName")[0]
    return db_dict


def save(db_dict):
    timestamp = date.today().strftime('%Y%m%d')
    db_dict["id"] = timestamp + ste
    db_dict["change_amount"] = ""
    db_dict["change_range"] = ""
    db_dict["price_date"] = date.today().strftime('%Y/%m/%d')
    db_dict["raw_type"] = ste
    db_dict["source"] = "中国不锈钢交易网"
    db_dict["create_time"] = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    insert_db(db_dict)


def run():
    try:
        py = request()
        db_dict = parse(py)
        save(db_dict)
    except Exception as e:
        log1.error(e)
    log1.info("不锈钢END!")


if __name__ == '__main__':
    run()